﻿#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using std::cin;
using std::cout;
using std::endl;
using std::string;
#define BUF_SIZE 1024
void Error(const string &msg)
{
  cout << msg << " error!" << endl;
}
void Print(const string &msg, int size = 0)
{
  cout << msg;
  if (size != 0)
    cout << size << endl;
}
int main(int args, char *argv[])
{
  // 创建套接字对象
  int sock_tcp = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  int sock_udp = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (sock_tcp == -1)
    Error("sock_tcp: socket() error!");
  if (sock_udp == -1)
    Error("sock_udp: socket() error!");
  // getsockopt():SOL_SOCKET->SO_SNDBUF
  int sndBuf_tcp{0};
  socklen_t len_tcp_out = sizeof(sndBuf_tcp);
  if (getsockopt(sock_tcp, SOL_SOCKET, SO_SNDBUF, (char *)&sndBuf_tcp, &len_tcp_out) == -1)
    Error("sock_tcp: getsockopt(SO_SNDBUF) error!");
  else
    Print("sndBuf_tcp=", sndBuf_tcp);
  int sndBuf_udp{0};
  socklen_t len_udp_out = sizeof(sndBuf_udp);
  if (getsockopt(sock_udp, SOL_SOCKET, SO_SNDBUF, (char *)&sndBuf_udp, &len_udp_out) == -1)
    Error("sock_udp: getsockopt(SO_SNDBUF) error!");
  else
    Print("sndBuf_udp=", sndBuf_udp);
  Print("************************************************\n");

  // getsockopt():SOL_SOCKET->SO_RCVBUF
  int rcvBuf_tcp{0};
  socklen_t len_tcp_in = sizeof(rcvBuf_tcp);
  if (getsockopt(sock_tcp, SOL_SOCKET, SO_RCVBUF, (char *)&rcvBuf_tcp, &len_tcp_in) == -1)
    Error("sock_tcp: getsockopt(SO_RCVBUF) error!");
  else
    Print("rcvBuf_tcp=", rcvBuf_tcp);
  int rcvBuf_udp{0};
  socklen_t len_udp_in = sizeof(rcvBuf_udp);
  if (getsockopt(sock_udp, SOL_SOCKET, SO_RCVBUF, (char *)&rcvBuf_udp, &len_udp_in) == -1)
    Error("sock_udp: getsockopt(SO_RCVBUF) error!");
  else
    Print("rcvBuf_udp=", rcvBuf_udp);
  Print("************************************************\n");
  // getsockopt():IPPROTO_IP->TTL
  int ttl{0};
  socklen_t len_ttl = sizeof(ttl);
  if (getsockopt(sock_tcp, IPPROTO_IP, IP_TTL, (char *)&ttl, &len_ttl) == -1)
    Error("sock_tcp: getsockopt(TTL) error!");
  else
    Print("TTL=", ttl);
  Print("************************************************\n");

  // setsockopt()
  ttl = 34;
  if (setsockopt(sock_tcp, IPPROTO_IP, IP_TTL, (char *)&ttl, len_ttl) == -1)
    Error("sock_udp: setsockopt(TTL) error!");
  if (getsockopt(sock_tcp, IPPROTO_IP, IP_TTL, (char *)&ttl, &len_ttl) == -1)
    Error("sock_tcp: getsockopt(TTL) error!");
  else
    Print("TTL=", ttl);
  close(sock_tcp);
  close(sock_udp);
  return 0;
}